<template>
  <div class="purchase-orders-management">
    <!-- 统计概览 -->
    <PurchaseOrderStats :stats="stats" />
    
    <!-- 筛选条件 -->
    <PurchaseOrderFilter 
      :query-params="queryParams"
      :suppliers="suppliers"
      @update:query-params="handleQueryParamsUpdate"
      @search="handleQuery"
      @reset="handleReset"
    />
    
    <!-- 订单列表 -->
    <PurchaseOrderTable
      :purchase-orders="tableData"
      :loading="loading"
      :pagination="pagination"
      :selected-orders="selectedOrders"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
      @sort="handleSort"
      @view-detail="handleViewDetail"
      @edit="handleEdit"
      @more-action="handleMoreAction"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @column-settings="showColumnSettings"
    />
    
    <!-- 操作对话框 -->
    <PurchaseOrderOperationDialog
      v-model="operationDialogVisible"
      :editing-order="currentOrder"
      :suppliers="suppliers"
      @submit="handleOperationSuccess"
      @close="handleOperationClose"
    />
    
    <!-- 详情对话框 -->
    <PurchaseOrderDetailDialog
      v-model="detailDialogVisible"
      :order="currentOrder"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup lang="ts">
// 使用完整的路径导入 Vue API
import { ref, reactive, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  Document, Clock, Check, Upload, Operation, 
  Download, Plus, Setting, Sort, Printer, 
  Van, Close, Delete, ArrowDown, Refresh, Search, SetUp
} from '@element-plus/icons-vue'

// 导入拆分的组件
import PurchaseOrderStats from './components/PurchaseOrderStats.vue'
import PurchaseOrderFilter from './components/PurchaseOrderFilter.vue'
import PurchaseOrderTable from './components/PurchaseOrderTable.vue'
import PurchaseOrderOperationDialog from './components/PurchaseOrderOperationDialog.vue'
import PurchaseOrderDetailDialog from './components/PurchaseOrderDetailDialog.vue'

// 导入API
import { getPurchaseOrders, getPurchaseOrderStats } from '@/api/procurement'

// 使用API中定义的数据模型
import type { PurchaseOrder } from '@/api/procurement'

interface Supplier {
  id: number
  name: string
}

interface PurchaseOrderStatsData {
  totalOrders: number
  pendingOrders: number
  completedOrders: number
  monthlyAmount: number
  supplierCount: number
  orderTrend: number
  pendingTrend: number
  amountTrend: number
  supplierTrend: number
  completedOrderTrend: number
  pendingOrderTrend: number
}

interface QueryParams {
  orderNumber: string
  supplierId: number | null
  status: string
  orderDateRange: string[]
  minAmount: number | undefined
  maxAmount: number | undefined
  purchaser: string
  page: number
  limit: number
}

// 响应式数据
const loading = ref(false)
const importLoading = ref(false)
const exportLoading = ref(false)
const printLoading = ref(false)

// 统计数据
const stats = reactive<PurchaseOrderStatsData>({
  totalOrders: 0,
  pendingOrders: 0,
  completedOrders: 0,
  monthlyAmount: 0,
  supplierCount: 0,
  orderTrend: 0,
  pendingTrend: 0,
  amountTrend: 0,
  supplierTrend: 0,
  completedOrderTrend: 0,
  pendingOrderTrend: 0
})

// 查询参数
const queryParams = reactive<QueryParams>({
  orderNumber: '',
  supplierId: null,
  status: '',
  orderDateRange: [],
  minAmount: undefined,
  maxAmount: undefined,
  purchaser: '',
  page: 1,
  limit: 10
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<PurchaseOrder[]>([])
const suppliers = ref<Supplier[]>([
  { id: 1, name: '供应商A' },
  { id: 2, name: '供应商B' },
  { id: 3, name: '供应商C' }
])
const selectedOrders = ref<PurchaseOrder[]>([])

// 对话框控制
const operationDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentOrder = ref<PurchaseOrder | null>(null)

// 方法定义
// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getPurchaseOrderStats()
    if (response.success && response.data) {
      Object.assign(stats, response.data)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 生命周期
onMounted(async () => {
  // 加载统计数据
  await loadStats()
  // 加载表格数据
  loadTableData()
})

const loadTableData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize
    }
    
    if (queryParams.orderNumber) {
      params.orderNumber = queryParams.orderNumber
    }
    
    if (queryParams.supplierId) {
      params.supplierId = queryParams.supplierId
    }
    
    if (queryParams.status) {
      params.status = queryParams.status
    }
    
    if (queryParams.orderDateRange && queryParams.orderDateRange.length === 2) {
      params.startDate = queryParams.orderDateRange[0]
      params.endDate = queryParams.orderDateRange[1]
    }
    
    // 调用真实API获取采购订单列表
    const response = await getPurchaseOrders(params)
    
    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.pagination.total
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error('数据加载失败: ' + response.message)
    }
  } catch (error) {
    ElMessage.error('数据加载失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  currentOrder.value = null
  operationDialogVisible.value = true
}

const handleImport = () => {
  importLoading.value = true
  ElNotification({
    title: '导入提醒',
    message: '正在导入采购订单数据...',
    type: 'info'
  })
  setTimeout(() => {
    importLoading.value = false
    ElNotification({
      title: '导入成功',
      message: '采购订单数据导入完成',
      type: 'success'
    })
  }, 1500)
}

const handleExport = () => {
  exportLoading.value = true
  ElNotification({
    title: '导出提醒',
    message: '正在导出采购订单数据...',
    type: 'info'
  })
  setTimeout(() => {
    exportLoading.value = false
    ElNotification({
      title: '导出成功',
      message: '采购订单数据已导出至下载目录',
      type: 'success'
    })
  }, 1500)
}

const handlePrint = () => {
  printLoading.value = true
  ElNotification({
    title: '打印提醒',
    message: '正在准备打印...',
    type: 'info'
  })
  setTimeout(() => {
    printLoading.value = false
    ElNotification({
      title: '打印完成',
      message: '采购订单已发送至打印机',
      type: 'success'
    })
  }, 1500)
}

const handleRefresh = async () => {
  ElNotification({
    title: '刷新提醒',
    message: '正在刷新数据...',
    type: 'info'
  })
  await loadStats()
  loadTableData()
}

const handleViewDetail = (order: PurchaseOrder) => {
  currentOrder.value = order
  detailDialogVisible.value = true
}

const handleEdit = (order: PurchaseOrder) => {
  currentOrder.value = order
  operationDialogVisible.value = true
}

const handleDelete = (order: PurchaseOrder) => {
  ElMessageBox.confirm(
    `确定要删除采购订单 ${order.orderNumber} 吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(() => {
    // 模拟删除操作
    ElMessage.success(`采购订单 ${order.orderNumber} 删除成功`)
    loadTableData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchDelete = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要删除的采购订单')
    return
  }
  
  ElMessageBox.confirm(
    `确定要批量删除选中的 ${selectedOrders.value.length} 个采购订单吗？此操作不可恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(() => {
    // 模拟批量删除操作
    ElMessage.success('批量删除成功')
    loadTableData()
  }).catch(() => {
    ElMessage.info('已取消批量删除')
  })
}

const handleQuery = () => {
  ElNotification({
    title: '查询提醒',
    message: '正在查询采购订单...',
    type: 'info'
  })
  // 重置到第一页
  pagination.currentPage = 1
  loadTableData()
}

const handleReset = () => {
  // 重置查询条件
  queryParams.orderNumber = ''
  queryParams.supplierId = null
  queryParams.status = ''
  queryParams.orderDateRange = []
  queryParams.minAmount = undefined
  queryParams.maxAmount = undefined
  queryParams.purchaser = ''
  ElNotification({
    title: '重置提醒',
    message: '查询条件已重置',
    type: 'info'
  })
  // 重置到第一页
  pagination.currentPage = 1
  loadTableData()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1  // 页大小改变时回到第一页
  loadTableData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadTableData()
}

const handleSelectionChange = (selection: PurchaseOrder[]) => {
  selectedOrders.value = selection
}

const handleRowClick = (row: PurchaseOrder) => {
  // 行点击事件处理
  handleViewDetail(row)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  // 排序变化事件处理
}

const handleSort = (field: string) => {
  // 排序事件处理
}

const handleMoreAction = (command: { action: string, row: PurchaseOrder }) => {
  switch (command.action) {
    case 'print':
      handlePrint()
      break
    case 'export':
      handleExport()
      break
    case 'delete':
      handleDelete(command.row)
      break
    default:
      ElMessage.info('未知操作')
  }
}

const showColumnSettings = () => {
  // 显示列设置
}

// 对话框相关方法
const handleOperationSuccess = (order: PurchaseOrder) => {
  operationDialogVisible.value = false
  loadTableData()
}

const handleOperationClose = () => {
  operationDialogVisible.value = false
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentOrder.value = null
}

// 查询参数更新处理
const handleQueryParamsUpdate = (newParams: QueryParams) => {
  Object.assign(queryParams, newParams)
}
</script>